import numpy as np
import pickle
from flask import Flask,request,jsonify

app = Flask('churn')
def predict_single(customer,dv,model):
    X = dv.transform([customer])
    y_pred = model.predict_proba(X)[:,1]
    return y_pred[0]

with open('churn-model.bin','rb') as f_in:
    dv,model = pickle.load(f_in)

customer={
    'gender':'female','seniorcitizen':0,'partner':'no','dependents':'no','phoneservice':'yes',
    'multiplelines':'no',
    'internetservice':'dsl','onlinesecurity':'yes','onlinebackup':'no','deviceprotection':'yes','techsupport':'yes',
    'streamingtv':'yes','streamingmovies':'yes','contract':'one_year','paperlessbilling':'yes','paymentmethod':'bank_transfer_(automatic)',
    'tenure':41,'monthlycharges':79.85,'totalcharges':3320.75
}

@app.route('/')
def index():
    return 'hello index'




@app.route('/predict',methods=['POST'])
def predict():
    customer = request.get_json() # 获取json格式的请求内容
    prediction = predict_single(customer,dv,model) # 为客户评分
    churn = prediction>=0.5
    result = {
        'churn_probability':float(prediction),
        'churn':bool(churn)
    }
    return jsonify(result) # 将响应转化为json

# prediction = predict_single(customer,dv,model)
# print("{:.3f}".format(prediction))
#
# if prediction >=0.5:
#     print('churn')
# else:
#     print('no churn')
if __name__ =='__main__':
    app.run(debug=True,host='127.0.0.1',port=9696)